package com.example.pet.util;

import com.example.pet.entity.User;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class SessionUtil {

    private static final String SESSION_USER = "SESSION_USER";
    private static final String SESSION_USER_ID = "SESSION_USER_ID";

    private static HttpSession getSession() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return request.getSession();
    }

    public static void setUser(User user) {
        HttpSession session = getSession();
        session.setAttribute(SESSION_USER,user);
        session.setAttribute(SESSION_USER_ID,user.getId());
    }

    public static User getUser() {
        HttpSession session = getSession();
        return (User) session.getAttribute(SESSION_USER);
    }

    public static Integer getUserId() {
        HttpSession session = getSession();
        return (Integer) session.getAttribute(SESSION_USER_ID);
    }

    public static void logout() {
        HttpSession session = getSession();
        session.invalidate();
    }

}
